import './presetVar';
import React, { Component } from 'react';
import { createPage, base, high, promptBox, toast,pageTo } from 'nc-lightapp-front';
import { tableButtonClick, pageButtonClick, beforeEvent, afterEvent, invoiceEvent, refreshButtonClick } from './events';
import { onBatchChange, setImportConfig } from './events/afterEvent';
import initTemplate, { routeChange,setDefautValueAfterBodyAdd } from './initTemplate';
import LinkQueryFyytModel from 'src/erm/sscrppublic/common/linkquery/LinkQueryFyytModel';
import AllUserGridRef from 'sscrp/refer/rpbill/AllUserGridRef';
import { getAfterEventParams } from 'src/erm/sscrppublic/common/utils/formulaUtils';
import requestApi from "./requestApi";
import { beforeUpdatePage, updatePage } from 'src/erm/sscrppublic/common/utils/updatePage';
import { updataFormData, updatacardTableData, setcardTableData } from 'src/erm/sscrppublic/common/utils/changePageData';
import GetPageData from 'src/erm/sscrppublic/common/utils/getPageData';
import pubMessage from 'src/erm/sscrppublic/common/utils/pubMessage';
import getAttachmentLength from '../../../public/components/linkAttachment/getAttachmentLength';
import Cjk from '../../expenseaccount4Cjk/card/index.js';
import Fyyt from '../../expenseaccount4Fyyt/card/index.js';
import InvoiceWallet from '../../wallet/card/index';
import UploadInvoice from './components/UploadInvoice';
import QuickShare from './components/QuickShare';
// import _ from "lodash-es"
import ExpenseaccountForPull from './components/expenseaccount4Pull/card/index';//添加制单弹窗

import { excludeBodyKey, getZzhllxValue, zzhllxLogic, rowExists } from './ExpenseUtils';
import { viewModel } from 'nc-lightapp-front';
import attachments from 'uap/common/components/getAttachmentInfo';
import { updateAttachment } from './events/pageButtonClick'
import LoanDetail from '../../loandetail/card';
import { get } from 'lodash-es'
import {dataHandle} from './initTemplate'
const { getAttachments, getAttachmentsInfo } = attachments;
let { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;
let { NCModal, NCButton, NCPopover, NCIcon, NCLoading } = base;
//引入侧边栏
import AuditSidebar from 'sscia/auditSidebar/components/auditSidebar'
import {relateVoiceEvent} from './events/tableExtendButtonClick'
import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTable,
    CardTableGroup,
    ButtonGroup,
    MultiButtonGroup
} from 'src/erm/sscrppublic/common/components/bill';

import './index.less';
import LinkQueryJkbxModel from 'src/erm/sscrppublic/common/linkquery/LinkQueryJkbxModel';
import LinkQueryFysqModel from 'src/erm/sscrppublic/common/linkquery/LinkQueryFysqModel';
import { renderButtions } from './initTemplate';
import Inspection from 'epmp/exports/components/Inspection';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import ApprovalTrans from 'uap/common/components/approvalTrans';

const pageButton = window.presetVar.pageButton;
pageButton.pageCjk = "pageCjk";
pageButton.pageFyyt = "pageFyyt";
let ntbCheck = 'false';
let proBudgetCheck = 'false';

// xuzd5 适配到1909
function getRequest1(url) {
    if (!url)
        url = document.location.search;
    let sessionInfo = ""
    if (url.indexOf("page=") != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf("?") != -1) {
            var str = url.substring(url.indexOf("?") + 1);
            var strs = str.split("&");
            page = strs[0].split("=")[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf("?") != -1) {
        sessionInfo = url.substring(url.indexOf("?") + 1);
    } else {
        sessionInfo = url;
    }


    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}

window.assingUsers = [];
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk

window.bxcontrastGrid = {};
window.accruedverifyGrid = {};

class jkbxBillCard extends Component {
    constructor(props) {
        super();
        //初始化侧边栏
        this.auditSidebar = new AuditSidebar();
        this.state = {
            showSMFPModal: false,
            showCJKModal: false,
            showFyytModal: false,
            showUploader: false,
            modalControl: false,
            fileList: [],
            target: null,
            billId: '',
            showLinkQueryFysqModel: false,
            showLinkQueryFyytModel: false,
            showLinkQueryJkbxModel: false,
            sourceData: null,
            showLinkBudget: false,
            allUserGridRefValue: {},
            showBillShare: false,
            hideTables: ['er_bxcontrast','accrued_verify','invoice_Detail','er_cshare_detail'],
            ShowApproveDetail: false,
            billtype: '',
            compositedata: '',
            compositedisplay: '',
            transtype_name: '',
            linkData: '',
            groupLists: [],
            iss: false,
            sscivmInvoiceData: {},
            showInvoiceRelate:false,//关联发票控制
            currentRowInvoiceRelate: {},//关联发票当前行
            showInvoiceWallet: false,  //票夹控制
            showUploadInvoice: false,  //上传控制
            showTableUploader: false,  //控制表体关联发票列表显示
            reqTableAttachParam:{}, //请求表体关联发票参数
            uploaderBtnDisable: false, //附件上传按钮可用状态
            showLoanDetailModel: false,
			closeQuickShare: false ,//快速分摊
            invoiceRelatePk: [], //关联发票对应票据的贫困集合

            // 预览图片的路径
            previewImgUrl: "",

            showApplicationFormModal: false,//关联申请单弹窗

            billApplicationFormData:{},

            isShowover:false,//是否超标
            djzt:'0',
            showAuditSidebar:false,
            isShowLoading: false
        }
        this.auditSidebarTimeout = null
        this.pubMessage = new pubMessage(props);
        this.getPageDataUtil = new GetPageData(props, ['bbhl', 'tax_rate', 'groupbbhl', 'globalbbhl', 'rowno']);
        this.closesmfp = this.closesmfp.bind(this);
        this.closecjk = this.closecjk.bind(this);
        this.closefyyt = this.closefyyt.bind(this);
        this.cjk = this.cjk.bind(this);
        this.save = this.save.bind(this);
        this.submit = this.submit.bind(this);
        this.closeInvoiceWalletModal = this.closeInvoiceWalletModal.bind(this);
        this.multiLangJson = '';

        initTemplate.call(this, props);
        window.pageCjkClick = (cjkdata) => {
            console.log(this.props);
            console.log(props);
            let bodys = Object.values(window.presetVar.body);
            // let bodyarr = [];
            // let hideTable = this.state.hideTables;
            // bodys.forEach((one) => {
            //     if (hideTable.indexOf(one) < 0) {
            //         bodyarr[bodyarr.length] = one;
            //     }
            // })
            let appcode = (props.getUrlParam("appcode") == undefined || props.getUrlParam("appcode") == '') ? props.getSearchParam("c") : props.getUrlParam("appcode");
            let pagecode = (props.getUrlParam("pagecode") == undefined || props.getUrlParam("pagecode") == '') ? props.getSearchParam("p") : props.getUrlParam("pagecode");
            //bodyarr.push('er_bxcontrast')//必须要传
            let billdata = props.createExtCardData(pagecode, "head", bodys);
            requestApi.delete3status(billdata);  //过滤掉删除的行数据
            billdata.head.userjson = JSON.stringify(cjkdata);
            this.setState({ showCJKModal: false });
            billdata.templetid = props.meta.getMeta().pageid;
            requestApi.BillCjk({
                data: billdata,
                success: (data) => {
                    props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                   
                    let erbxcontrast = _.get(data,'bodys.er_bxcontrast.rows',[]) 
                    let hideTable = this.state.hideTables

                    if(erbxcontrast.length){
                        let index = hideTable.indexOf('er_bxcontrast')
                        if(index>-1){ //如果隐藏里面有，去掉
                            hideTable.splice(index,1)
                        }

                    }else{
                        hideTable.push('er_bxcontrast')
                    }
                    this.setState({hideTables:hideTable})
                    Object.keys(data.bodys).forEach((item) => {
                        let newitemdata = data.bodys[item];
                        if (item == 'arap_bxbusitem') {
                            newitemdata && newitemdata.rows && newitemdata.rows.forEach((itemData) => {
                                if(itemData && itemData.values && itemData.values.cjkybje && Number(itemData.values.cjkybje.value) !== 0){
                                    props.cardTable.setEditableByRowId('arap_bxbusitem', itemData.rowid, 'iscompanypay', false);
                                } else {
                                    props.cardTable.setEditableByRowId('arap_bxbusitem', itemData.rowid, 'iscompanypay', true);
                                }
                            })
                        }
                        if (item === 'er_bxcontrast') {
                            newitemdata && newitemdata.rows && newitemdata.rows.forEach((itemData) => {
                                itemData.values.cjkybje.scale = itemData.values.cjkybje.value.split('.')[1].length;
                            })
                            props.cardTable.setStatus(item, window.presetVar.status.browse);
                        } else {
                            if(newitemdata&&newitemdata.rows){
                                let rows = []
                                for(let i=0;i<newitemdata.rows.length;i++){
                                    if(newitemdata.rows[i].values&&newitemdata.rows[i].values.tablecode&&newitemdata.rows[i].values.tablecode.value == item){
                                        rows[rows.length] = newitemdata.rows[i];
                                    } else if(item === 'er_cshare_detail' || item === 'accrued_verify' || item === 'invoice_Detail') { //分摊没有tablecode，不走过滤,核销预提没有tablecode
                                        rows[rows.length] = newitemdata.rows[i];
                                    }
                                }
                                newitemdata.rows = rows;
                            }
                        }
                        newitemdata && props.cardTable.setTableData(item, newitemdata, null, false);
                        updatePage(props, 'head', window.presetVar.lsBodys);
                    })
                },
                error: (data) => {
                    toast({ content: data.message, color: 'danger' });
                }
            });
        };
        window.pageInvoiceToBxClick = (pjdata,fpdata) => {
            let bodys = Object.values(window.presetVar.body);
            // let bodyarr = [];
            // let hideTable = this.state.hideTables;
            // bodys.forEach((one) => {
            //     if (hideTable.indexOf(one) < 0) {
            //         bodyarr[bodyarr.length] = one;
            //     }
            // })
            let appcode = (props.getUrlParam("appcode") == undefined || props.getUrlParam("appcode") == '') ? props.getSearchParam("c") : props.getUrlParam("appcode");
            let pagecode = (props.getUrlParam("pagecode") == undefined || props.getUrlParam("pagecode") == '') ? props.getSearchParam("p") : props.getUrlParam("pagecode");
            let tablecode =  window.invoiceListQueryParam && window.invoiceListQueryParam.tablecode
            let billdata = props.createExtCardData(pagecode, "head", bodys);
            let uj = {
                "appcode" : appcode,
                "pagecode" : pagecode,
                "templateid" :  props.meta.getMeta().pageid,
                tablecode,
                tablecodeSpilt: fpdata
            }
            pjdata = Object.assign(uj, pjdata);
            billdata.userjson = JSON.stringify(pjdata);
            billdata.templetid = props.meta.getMeta().pageid;
            this.setState({showInvoiceWallet: false})

            console.log(billdata,'billdata=====================')
            requestApi.transfer2Table({
                data: billdata,
                success: (data) => {
                    beforeUpdatePage(props);
                    // 全局化各页签与发票明细映射
                    window.presetVar.invoiceToBx = JSON.parse(data.userjson).invoiceToBx
                    window.presetVar.bxToInvoice = JSON.parse(data.userjson).bxToInvoice
                    //设置表头数据
                    let filterdata = requestApi.filterDatas(data.head[presetVar.head.head1]);
                    updataFormData(props, presetVar.head.head1, filterdata);
                    // BTM 性能优化，变更页面数据更新方法
                    window.presetVar.reloadHead = filterdata;
                    //设置表体数据
                    let hideTable = this.state.hideTables
                    Object.keys(data.bodys).forEach((moduleid) => {
                        let indexs = hideTable.indexOf(moduleid)
                        if(indexs>-1){
                            hideTable.splice(indexs,1)
                        }
                        this.setState({hideTables:hideTable})
                        let filterbodydatas = requestApi.filterDatas(data.bodys[moduleid]);
                        setcardTableData(props, moduleid, filterbodydatas)
                        updatacardTableData(props, moduleid, filterbodydatas);

                        filterbodydatas.rows.forEach((item,index) => {
                            let rate_category = getZzhllxValue(get(item.values,'zzhllx.rate_category',''),window.presetVar.zzhllxs)  // Y:五种中的一种，N:非五种，-1：空
                            let currentrow_bzbm = item.values.bzbm
                            zzhllxLogic(currentrow_bzbm,rate_category,'body',props,moduleid,item.rowid)
                        })
                        // props.cardTable.setTableDataWithResetInitValue(moduleid, filterbodydatas);
                        // updatePage(props, presetVar.head.head1, [moduleid]);
                    })
                },
                error: (data) => {
                    toast({ content: data.message, color: 'danger' });
                }
            });
        };
        window.pageTravelOrderToBxClick = (pjdata,fpdata) => {
            let bodys = Object.values(window.presetVar.body);
            let appcode = (props.getUrlParam("appcode") == undefined || props.getUrlParam("appcode") == '') ? props.getSearchParam("c") : props.getUrlParam("appcode");
            let pagecode = (props.getUrlParam("pagecode") == undefined || props.getUrlParam("pagecode") == '') ? props.getSearchParam("p") : props.getUrlParam("pagecode");
            let tablecode =  window.invoiceListQueryParam && window.invoiceListQueryParam.tablecode
            let billdata = props.createExtCardData(pagecode, "head", bodys);
            let uj = {
                "appcode" : appcode,
                "pagecode" : pagecode,
                "templateid" :  props.meta.getMeta().pageid,
                tablecode,
                tablecodeSpilt: fpdata
            }
            pjdata = Object.assign(uj, pjdata);
            billdata.userjson = JSON.stringify(pjdata);
            billdata.templetid = props.meta.getMeta().pageid;
            this.setState({showInvoiceWallet: false})

            console.log(billdata,'billdata=====================')
            requestApi.transferTravelOrderTable({
                data: billdata,
                success: (data) => {
                    beforeUpdatePage(props);
                    // 全局化各页签与发票明细映射
                    window.presetVar.invoiceToBx = JSON.parse(data.userjson).invoiceToBx
                    window.presetVar.bxToInvoice = JSON.parse(data.userjson).bxToInvoice
                    //设置表头数据
                    let filterdata = requestApi.filterDatas(data.head[presetVar.head.head1]);
                    updataFormData(props, presetVar.head.head1, filterdata);
                    // BTM 性能优化，变更页面数据更新方法
                    window.presetVar.reloadHead = filterdata;
                    //设置表体数据
                    let hideTable = this.state.hideTables
                    Object.keys(data.bodys).forEach((moduleid) => {
                        let indexs = hideTable.indexOf(moduleid)
                        if(indexs>-1){
                            hideTable.splice(indexs,1)
                        }
                        this.setState({hideTables:hideTable})
                        let filterbodydatas = requestApi.filterDatas(data.bodys[moduleid]);
                        setcardTableData(props, moduleid, filterbodydatas)
                        updatacardTableData(props, moduleid, filterbodydatas);

                        filterbodydatas.rows.forEach((item,index) => {
                            let rate_category = getZzhllxValue(get(item.values,'zzhllx.rate_category',''),window.presetVar.zzhllxs)  // Y:五种中的一种，N:非五种，-1：空
                            let currentrow_bzbm = item.values.bzbm
                            zzhllxLogic(currentrow_bzbm,rate_category,'body',props,moduleid,item.rowid)
                        })
                        // props.cardTable.setTableDataWithResetInitValue(moduleid, filterbodydatas);
                        // updatePage(props, presetVar.head.head1, [moduleid]);
                    })
                },
                error: (data) => {
                    toast({ content: data.message, color: 'danger' });
                }
            });
        };
        window.pageFyytClick = (fyytdata) => {

            console.log(this.props);
            console.log(props);
            let bodys = Object.values(window.presetVar.body);
            // let bodyarr = [];
            // let hideTable = this.state.hideTables;
            // bodys.forEach((one) => {
            //     if (hideTable.indexOf(one) < 0) {
            //         bodyarr[bodyarr.length] = one;
            //     }
            // })
            let pagecode = (props.getUrlParam("pagecode") == undefined || props.getUrlParam("pagecode") == '') ? props.getSearchParam("p") : props.getUrlParam("pagecode");
            let billdata = props.createExtCardData(pagecode, "head", bodys);

            billdata.head.userjson = JSON.stringify(fyytdata);
            this.setState({ showFyytModal: false });

            requestApi.BillFyyt({
                data: billdata,
                success: (data) => {
                    props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                    let verifydata = _.get(data,'bodys.accrued_verify.rows',[]) 
                    let hideTable = this.state.hideTables

                    if(verifydata.length){
                        let index = hideTable.indexOf('accrued_verify')
                        if(index>-1){ //如果隐藏里面有，去掉
                            hideTable.splice(index,1)
                        }

                    }else{
                        hideTable.push('accrued_verify')
                    }
                    this.setState({hideTables:hideTable})

                    props.cardTable.setTableData("accrued_verify", {rows:verifydata}, null, false);

                    updatePage(props, 'head', window.presetVar.lsBodys);
                },
                error: (data) => {
                    toast({ content: data.message, color: 'danger' });
                }
            });
        };
        // TOP NCCLOUD-61317 增加公式编辑后联动 chengwebc ADD
        props.setRelationAfterEventCallBack && props.setRelationAfterEventCallBack((props, changedField, changedArea, oldCard, newCard, index, rowId) => {
            let params = getAfterEventParams(props, changedField, changedArea, oldCard, newCard, index, rowId);
            params.map((one) => {
                afterEvent.call(this, props, one.moduleId, one.key, one.value, one.changedrows, one.index)
            })
        });
        // BTM NCCLOUD-61317 增加公式编辑后联动 chengwebc

        props.use.form('head');
    }
    closesmfp() {
        this.setState({ showSMFPModal: false });
    }
    closecjk() {
        this.setState({ showCJKModal: false });
    }
    closefyyt() {
        this.setState({ showFyytModal: false });
    }

    billInvalid() {

    }

    getTip(states){
        this.setState({isShowover:states})
    }
    componentDidMount() {
      this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
        })
    }

    componentDidUpdate() {

    }
    componentWillMount() {
        window.onbeforeunload = () => {
            let status = this.props.getUrlParam("status");
            let addType = this.props.getUrlParam('addType');

            if (addType != "pull" && (status == 'edit' || status == 'add')) {
                return ''/* 国际化处理： 确定要离开吗？*/
            }
        }
    }

    componentWillUnmount() {
        this.auditSidebarTimeout && clearTimeout(this.auditSidebarTimeout)
     }
    cancel() {
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info) {
        this.setState({
            showLinkBudget: false
        })
    }
    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }
    cjk() {
        window.isSaveLock = false; // 设置任务状态
        let bodys = Object.values(window.presetVar.body);
        // let bodyarr = [];
        // let hideTable = this.state.hideTables;
        // bodys.forEach((one) => {
        //     if (hideTable.indexOf(one) < 0) {
        //         bodyarr[bodyarr.length] = one;
        //     }
        // })
        let param = {};
        param.tradetype = window.presetVar.tradetype;
        param.pk_jkbx = this.props.form.getFormItemsValue("head", "pk_jkbx").value;
        param.jkbxr = this.props.form.getFormItemsValue("head", "jkbxr").value;
        param.receiver = this.props.form.getFormItemsValue("head", "receiver").value;
        param.bzbm = this.props.form.getFormItemsValue("head", "bzbm").value;
        param.djrq = this.props.form.getFormItemsValue("head", "djrq").value;
        param.dwbm = this.props.form.getFormItemsValue("head", "dwbm").value;
        if (this.props.form.getFormItemsValue("head", "pk_item").value) {
            param.pk_item = this.props.form.getFormItemsValue("head", "pk_item").value;
        } else {
            param.pk_item = "~";
        }
        let bodyBZ = [];
        let pk_items = [];
        let bzjeMap = new Map();
        let showData = this.props.createExtCardData(this.props.meta.getMeta().code, "head", bodys);
        requestApi.delete3status(showData) //表体删除行过滤
        Object.keys(showData.bodys).forEach((item, index) => {
            // if (item == "arap_bxbusitem" || item == "bzitem" || item == "other" || item == "zsitem") {
            if(excludeBodyKey(item)) {
                showData.bodys[item].rows.forEach((row) => {
                    if (row.values.bzbm && row.values.bzbm.value) {
                        bodyBZ.push(row.values.bzbm);
                        var amount = row.values["vat_amount"].value;//取含税金额
                        if (bzjeMap.has(row.values.bzbm.value)) {
                            var oldAmount = parseFloat(bzjeMap.get(row.values.bzbm.value));
                            bzjeMap.delete(row.values.bzbm.value);
                            bzjeMap.set(row.values.bzbm.value, oldAmount + parseFloat(amount));
                        } else {
                            bzjeMap.set(row.values.bzbm.value, amount);
                        }
                    }
                    if (row.values.pk_item && row.values.pk_item.value){
                        pk_items.push(row.values.pk_item.value);
                    }
                });
            }
        });
        param.bzbms = bodyBZ;
        param.pk_items = pk_items;
        window.cjkdata = param;
        window.bxjeMap = bzjeMap;
        window.bxcontrastGrid = this.props.cardTable.getAllRows("er_bxcontrast");
        this.setState({ showCJKModal: true });
    }
    save() {
        // 避免重复 Ctrl + S 造成的报错,手动增加loading 
        if( window.isSaveLock || this.props.getUrlParam("status") === 'browse' ){  // 当前有任务在执行 或者是浏览态
            return
        }else{  
            window.isSaveLock = true // 设置任务状态
            //console.log('123123======================================')
        }

        let statusVar = window.presetVar.status;
        let billtype = window.presetVar.tradetype;
        let bodyarr = [];
        let hideTable = this.state.hideTables;
        let bodys = Object.values(window.presetVar.body);
        let sense = this.props.getUrlParam("scene");
        bodys.forEach((one) => {
            if (hideTable.indexOf(one) < 0) {
                bodyarr[bodyarr.length] = one;
            }
        })
        
        let billdata = this.props.createExtCardData(this.props.meta.getMeta().code, "head", bodys);
        requestApi.delete3status(billdata);  //过滤掉删除的行数据

        //不录入单据内容直接报错不能提交
        let multiLang_head = this.props.MutiInit.getIntl(2011); //this.moduleId
        let vat_amount = this.props.form.getFormItemsValue("head", ['iscostshare']) == null ? "" : this.props.form.getFormItemsValue("head", ['vat_amount'])[0].value//报销销金额
        if (vat_amount == undefined || vat_amount == null || vat_amount == 0) {
            toast({ content: multiLang_head && multiLang_head.get('201102BCLF-0020')/*"报销金额不能为空!"*/, color: 'warning' });
            window.isSaveLock = false; // 设置任务状态
            return;
        }

        let paramdata = {};
        console.log(billdata);
        paramdata.fromssc = "ssc",
            paramdata.jkCheck = "",
            paramdata.ntbCheck = ntbCheck,
            paramdata.proBudgetCheck = proBudgetCheck,
            paramdata.msg_pk_bill = "",
            paramdata.accessorybillid = this.accessorybillid;
        paramdata.pk_tradetype = window.presetVar.tradetype;
        let pagecode = (this.props.getUrlParam("pagecode") == undefined || this.props.getUrlParam("pagecode") == '') ? this.props.getSearchParam("p") : this.props.getUrlParam("pagecode");
        let appcode = (this.props.getUrlParam("appcode") == undefined || this.props.getUrlParam("appcode") == '') ? this.props.getSearchParam("c") : this.props.getUrlParam("appcode");
        paramdata.pagecode = pagecode;
        paramdata.appcode = appcode;
        let status = this.props.getUrlParam("status");
        if (status == "edit") {
            paramdata.status = "edit";
        } else {
            paramdata.status = "save";
        }
        billdata.head.userjson = JSON.stringify(paramdata);
        billdata.templetid = this.props.meta.getMeta().pageid;
        console.log(billdata);
        this.props.validateToSave(billdata, () => {
            requestApi.savejkbx({
                data: billdata,
                success: (data) => {
                    let props = this.props;
                    console.log(data);
                    if(data.success==='false'){
                        window.isSaveLock = false; // 设置任务状态
                        return
                    }
                    if (data.head && data.head.head && data.head.head.rows && data.head.head.rows.length) {
                        updateAttachment(data.head.head.rows[0].values.pk_jkbx.value, this)
                    }
                    let billid = get(data, 'head.head.rows[0].values.pk_jkbx.value');
                    let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                    if (data.userjson && JSON.parse(data.userjson) && JSON.parse(data.userjson).reimmsg && JSON.parse(data.userjson).reimmsg.length > 0) {
                        promptBox({
                            color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                            title: multiLang && multiLang.get('201102JCLF_C-0002'),
                            content: JSON.parse(data.userjson).reimmsg,
                            
                            beSureBtnName: multiLang && multiLang.get('2011-0003'),
                            cancelBtnName: multiLang && multiLang.get('2011-0002'),
                            beSureBtnClick: () => {
                                
                                window.presetVar.redata = 'Y';
                                if (sense && (sense == "approve" || sense == "zycl" || sense == "approvesce")) {
                                    pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, tradetype: billtype, scene: sense });
                                } else {
                                    pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, pagecode: pagecode});

                                }
                                routeChange.call(this, this.props)
                                this.auditSidebar.refreshSidebar()
                                window.isSaveLock = false; // 设置任务状态
                            },   // 确定按钮点击调用函数,非必输
                            cancelBtnClick: () => {
                                
                                let newFormData = requestApi.filterDatas(data.head[presetVar.head.head1]);
                                updataFormData(props, presetVar.head.head1, newFormData);
                                window.presetVar.reloadHead = newFormData;
                                bodyarr.forEach((item) => {
                                    updatacardTableData(props, item, requestApi.filterDatas(data.bodys[item]));
                                })
                                if (sense && (sense == "approve" || sense == "zycl" || sense == "approvesce")) {
                                    pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.edit, id: billid, tradetype: billtype, scene: sense });
                                } else {
                                    pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.edit, id: billid, pagecode: pagecode});
                                }
                                routeChange.call(this, this.props)
                                this.auditSidebar.refreshSidebar()
                                window.isSaveLock = false; // 设置任务状态
                            }  // 取消按钮点击调用函数,非必输
                        })
                        window.isSaveLock = false; // 设置任务状态
                    } else {
                        if (data.Alarm && data.Alarm == "Y") {
                            promptBox({
                                color: 'danger',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                title: multiLang && multiLang.get("201102BCLF-0021"),                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                                content: data.message,             // 提示内容,非必输
                                
                                beSureBtnName: multiLang && multiLang.get("201102BCLF-0017"),          // 确定按钮名称, 默认为"确定",非必输
                                cancelBtnName: multiLang && multiLang.get("201102BCLF-0018"),         // 取消按钮名称, 默认为"取消",非必输
                                beSureBtnClick: () => {
                                    if (data.AlarmType && data.AlarmType == "Project"){
                                        proBudgetCheck = 'true';
                                    }else{
                                        ntbCheck = 'true';
                                    }
                                    this.save();
                                },   // 确定按钮点击调用函数,非必输
                                // cancelBtnClick: ()=>{console.log("sdd") },  // 取消按钮点击调用函数,非必输
                            })
                            window.isSaveLock = false; // 设置任务状态
                        } else {
                            let newFormData = requestApi.filterDatas(data.head[presetVar.head.head1]);
                            updataFormData(this.props, presetVar.head.head1, newFormData);
                            window.presetVar.reloadHead = newFormData;
                            // BTM 性能优化，变更页面数据更新方法
                            bodyarr.forEach((item) => {
                                // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                // debugLogs.timeStart('setTableData_' + item);
                                // props.cardTable.setTableData(item, requestApi.filterDatas(data.bodys[item]));
                                // debugLogs.timeEnd('setTableData_' + item);
                                updatacardTableData(this.props, item, requestApi.filterDatas(data.bodys[item]));
                                // BTM 性能优化，变更页面数据更新方法
                            })
                            if (data.AlarmType && data.AlarmType == "Project"){
                                proBudgetCheck = 'false';
                            }else{
                                if (data.proBudgetCheck && data.proBudgetCheck == "Y"){
                                    proBudgetCheck = 'true';
                                }
                                ntbCheck = 'false';
                            }
                            window.presetVar.redata = 'N';
                            if (sense && (sense == "approve" || sense == "zycl" || sense == "approvesce")) {
                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, tradetype: billtype, scene: sense });
                            } else {
                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, pagecode: pagecode});
                            }
                            routeChange.call(this, this.props)
                            this.auditSidebar.refreshSidebar()
                            window.isSaveLock = false; // 设置任务状态
                        }

                    }

                },
                error: (data) => {
                    toast({ content: data.message, color: 'danger' });
                    window.isSaveLock = false; // 设置任务状态
                }
            });
        }, bodyarr, null);

    }
    submit() {
        let billtype = window.presetVar.tradetype;
        let statusVar = window.presetVar.status;
        let bodys = Object.values(window.presetVar.body);
        let bodyarr = [];
        let hideTable = this.state.hideTables;
        let sense = this.props.getUrlParam("scene");
        bodys.forEach((one) => {
            if (hideTable.indexOf(one) < 0) {
                bodyarr[bodyarr.length] = one;
            }
        })
        let billdata = this.props.createExtCardData(this.props.meta.getMeta().code, "head", bodyarr);
        requestApi.delete3status(billdata);  //过滤掉删除的行数据
        let appcode = (this.props.getUrlParam("appcode") == undefined || this.props.getUrlParam("appcode") == '') ? this.props.getSearchParam("c") : this.props.getUrlParam("appcode");
        let pagecode = (this.props.getUrlParam("pagecode") == undefined || this.props.getUrlParam("pagecode") == '') ? this.props.getSearchParam("p") : this.props.getUrlParam("pagecode");
        let paramdata = {};
        console.log(billdata);
        paramdata.openbillid = !(this.props.getUrlParam("billid") || this.props.getUrlParam("id") || this.state.billId) ? "" : this.props.getUrlParam("billid") || this.props.getUrlParam("id") || this.state.billId;
        paramdata.fromssc = "ssc",
            paramdata.jkCheck = "",
            paramdata.ntbCheck = ntbCheck,
            paramdata.proBudgetCheck = proBudgetCheck,
            paramdata.msg_pk_bill = "",
            paramdata.pk_tradetype = window.presetVar.tradetype;
        paramdata.pagecode = pagecode;
        paramdata.appcode = appcode;
        let status = this.props.getUrlParam("status");
        if (status == "edit") {
            paramdata.status = "edit";
        } else if (status == "browse") {
            paramdata.status = "browse";
        } else {
            paramdata.status = "save";
        }
        if (window.sureAssign) {
            paramdata.status = "edit";
        }
        billdata.head.userjson = JSON.stringify(paramdata);
        billdata.templetid = this.props.meta.getMeta().pageid;
        this.props.validateToSave(billdata, () => {
            requestApi.submitBill({
                data: billdata,
                success: (data) => {
                    let props = this.props;
                    let multiLang = this.props.MutiInit.getIntl(2011);
                    if (data.workflow && (data.workflow == 'approveflow' || data.workflow == 'workflow')) {
                        this.setState({
                            compositedata: data,
                            compositedisplay: true
                        });
                        window.assignBillId = data.billid;
                        //重新给页面赋值
                        let newFormData = requestApi.filterDatas(data.bill.head[presetVar.head.head1]);
                        updataFormData(props, presetVar.head.head1, newFormData);
                        window.presetVar.reloadHead = newFormData;
                        bodyarr.forEach((item) => {
                            updatacardTableData(props, item, requestApi.filterDatas(data.bill.bodys[item]));
                        })
                    } else {
                        this.setState({
                            compositedisplay: false
                        });
                        if (data.Alarm && data.Alarm == "Y") {
                            promptBox({
                                color: 'danger',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                title: multiLang && multiLang.get("201102BCLF-0021"),                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                                content: data.message,             // 提示内容,非必输
                                
                                beSureBtnName: multiLang && multiLang.get("201102BCLF-0017"),          // 确定按钮名称, 默认为"确定",非必输
                                cancelBtnName: multiLang && multiLang.get("201102BCLF-0018"),         // 取消按钮名称, 默认为"取消",非必输
                                beSureBtnClick: () => {
                                    if (data.AlarmType && data.AlarmType == "Project"){
                                        proBudgetCheck = 'true';
                                    }else{
                                        ntbCheck = 'true';
                                    }
                                    this.submit();
                                },
                                cancelBtnClick: () => {
                                    let billid = props.form.getFormItemsValue("head", "pk_jkbx").value;
                                    let paramurl = getRequest1(parent.window.location.hash);
                                    if (props.getUrlParam('status') === 'browse') {
                                        pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, tradetype: billtype, pagecode: paramurl.p, appcode: paramurl.c });
                                        routeChange.call(this, this.props)
                                    } else {
                                        if (billid) {
                                            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.edit, id: billid, pagecode: paramurl.p});
                                            routeChange.call(this, this.props)
                                        } else {
                                        }

                                    }
                                    window.assingUsers = [];    //清空指派人信息
                                    window.sureAssign = false;
                                }
                            })
                        } else if (data.userjson && JSON.parse(data.userjson) && JSON.parse(data.userjson).reimmsg && JSON.parse(data.userjson).reimmsg.length > 0) {
                            promptBox({
                                color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                title: multiLang && multiLang.get('201102JCLF_C-0002'),
                                content: JSON.parse(data.userjson).reimmsg,
                                beSureBtnName: multiLang && multiLang.get('2011-0003'),
                                cancelBtnName: multiLang && multiLang.get('2011-0002'),
                                beSureBtnClick: () => {
                                    window.presetVar.redata = 'Y';
                                    let billid = data.head.head.rows[0].values.pk_jkbx.value;
                                    if (sense && (sense == "approve" || sense == "zycl" || sense == "approvesce")) {
                                        pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, tradetype: billtype, scene: sense });
                                    } else {
                                        pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, pagecode: pagecode});
                                    }
                                    routeChange.call(this, this.props)
                                }
                            })
                            if (data.AlarmType && data.AlarmType == "Project"){
                                proBudgetCheck = 'false';
                            }else{
                                if (data.proBudgetCheck && data.proBudgetCheck == "Y"){
                                    proBudgetCheck = 'true';
                                }
                                ntbCheck = 'false';
                            }
                        } else {
                            console.log(data);
                            let newFormData = requestApi.filterDatas(data.head[presetVar.head.head1]);
                            updataFormData(this.props, presetVar.head.head1, newFormData);
                            window.presetVar.reloadHead = newFormData;
                            // BTM 性能优化，变更页面数据更新方法
                            bodyarr.forEach((item) => {
                                // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                // debugLogs.timeStart('setTableData_' + item);
                                // props.cardTable.setTableData(item, requestApi.filterDatas(data.bodys[item]));
                                // debugLogs.timeEnd('setTableData_' + item);
                                updatacardTableData(this.props, item, requestApi.filterDatas(data.bodys[item]));
                                // BTM 性能优化，变更页面数据更新方法
                            })
                            if (data.AlarmType && data.AlarmType == "Project"){
                                proBudgetCheck = 'false';
                            }else{
                                if (data.proBudgetCheck && data.proBudgetCheck == "Y"){
                                    proBudgetCheck = 'true';
                                }
                                ntbCheck = 'false';
                            }
                            let billid = data.head.head.rows[0].values.pk_jkbx.value;
                            window.presetVar.redata = 'N';
                            if (sense && (sense == "approve" || sense == "zycl" || sense == "approvesce")) {
                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, tradetype: billtype, scene: sense });
                            } else {
                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: statusVar.browse, id: billid, pagecode: pagecode});
                            }
                            routeChange.call(this, this.props)
                            this.props.button.setButtonsVisible({
                                [pageButton.pageSave]: false,
                                [pageButton.pageEdit]: false,
                                [pageButton.billSubmit]: false,
                                [pageButton.billRecall]: true,
                                [pageButton.pageDel]: false,
                                [pageButton.billInvalid]: false,
                                [pageButton.pageClose]: false
                            });
                            window.assingUsers = [];    //清空指派人信息
                            window.sureAssign = false;
                        }
                    }


                },
                error: (data) => {
                    toast({ content: data.message, color: 'danger' });
                }
            });
        }, bodyarr, null);

    }

    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        this.setState({
            compositedisplay: false,
            isShowLoading: true
        });
        pageButtonClick.call(this)[pageButton.billSubmit]();
        window.assignBillId = '';
    }

    turnOff() {
        window.presetVar.fromBtn = 'turnOff'
        this.setState({
            compositedisplay: false
        });
        window.sureAssign = false;
        window.assingUsers = [];
        let props = this.props;
        let paramurl = getRequest1(parent.window.location.hash);
        let billid = window.assignBillId;
        if (!billid) {
            billid = props.form.getFormItemsValue("head", "pk_jkbx").value;
        }
        window.presetVar.redata = 'Y';
        pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html', { isfromSsc: true, status: window.presetVar.status.browse, id: billid, pagecode: paramurl.p });
        routeChange.call(this, this.props)
    }
    onHideUploader = () => {
        this.setState({
            showUploader: false,
        });
        let id = this.props.getUrlParam('id') || this.props.getUrlParam("billid") ? this.props.getUrlParam('id') || this.props.getUrlParam("billid") : this.state.billId;
        getAttachmentLength(id).then(lists => {
            this.setState({
                groupLists: lists
            });
            let button = this.props.button.getButtons();
            let multiLang = this.props.MutiInit.getIntl(2011);
            button.forEach((items) => {
                if (items.key == 'fileManager') {
                    // items.title = multiLang && multiLang.get('201102BCLF-0040') + ' ' + lists + ' ';
                    items.title = items.title.match( /[\u4e00-\u9fa5]/g).join("") + ' ' + lists + ' ';
                }
                this.props.button.setButtonTitle(items.key, items.title);
            });
            // this.props.button.setButtons(button);
            // renderButtions(this.props,this.props.meta.getMeta(),button,null);
        })
    }

    // 设置冲借款弹框里默认勾选的数据ligru
    setDefaultSelectedJk = (jkData, cjkProps) => {
        let props = this.props;
        let contrastGrid = props.cardTable.getAllRows("er_bxcontrast");
        let contrastPks = [];
        contrastGrid && contrastGrid.length && contrastGrid.forEach((contrastRow) => {
            if (contrastRow.values.pk_busitem && contrastRow.values.pk_busitem.value) {
                let contrastPk = contrastRow.values.pk_busitem.value;
                jkData && jkData.length && jkData.forEach((jk) => {
                    jk && jk.body && jk.body.jk_busitem && jk.body.jk_busitem.rows && jk.body.jk_busitem.rows.forEach((jkRow) => {
                        if (jkRow && jkRow.values && jkRow.values.pk_busitem.value === contrastPk) {
                            contrastPks.push(contrastPk);
                        }
                    })
                })
            }
        });
        cjkProps.transferTable.setTheCheckRows(window.cjkAreaCode.billsArea, contrastPks);

        //如果已经冲过借款，需要重新计算window.bxjeMap中的可冲销金额ligru
        let selectrow = cjkProps.transferTable.getTransferTableSelectedValue();
        selectrow && selectrow.head && selectrow.head.map((data) => {
            data.body.jk_busitem.rows.map((bodys) => {
                let bzbm = bodys.values.bzbm.value;
                window.bxjeMap.set(bzbm, parseFloat(window.bxjeMap.get(bzbm) - parseFloat(bodys.values.cjkybje.value) + parseFloat(bodys.values.hkybje.value)));
            })
        })
        // let btnObj = document.querySelector('.area-right .main-button');
        let btnObj = document.querySelector('.area-right .wui-button-text-wrap'); // 平台按钮元素更改，获取方式更改
        if (btnObj) {
            btnObj.addEventListener('click', function () {
                //判断是否有已选的条目，有就直接return，无则继续执行转单按钮正常逻辑
                let selectdata = cjkProps.transferTable.getTransferTableSelectedValue()
                if (selectdata && selectdata.head && selectdata.head.length > 0) {
                    return;
                }
                window.pageCjkClick(null);
            })
        }
    }

    // 设置核销预提弹框里默认勾选的数据
    setDefaultSelectedYt = (ytData, ytProps) => {
        let props = this.props;
        let accGrid = props.cardTable.getAllRows("accrued_verify");
        console.log(ytData, accGrid);
        let accPks = [];
        accGrid && accGrid.length && accGrid.forEach((accRow) => {
            if (accRow.values.pk_accrued_detail && accRow.values.pk_accrued_detail.value) {
                let accBodyPk = accRow.values.pk_accrued_detail.value;
                ytData && ytData.length && ytData.forEach((ytRow) => {
                    ytRow.body.accrued_detail.rows.forEach((ytBody) => {
                        if (ytBody.values.pk_accrued_detail && ytBody.values.pk_accrued_detail.value && ytBody.values.pk_accrued_detail.value === accBodyPk) {
                            accPks.push(accBodyPk);
                        }
                    })
                })
            }
        })
        ytProps.transferTable.setTheCheckRows(window.fyytAreaCode.billsArea, accPks);
        // let btnObj = document.querySelector('.area-right .main-button');
        let btnObj = document.querySelector('.area-right .wui-button-text-wrap'); // 平台按钮元素更改，获取方式更改
        if (btnObj) {
            btnObj.addEventListener('click', function () {
                //判断是否有已选的条目，有就直接return， 无则继续执行转单按钮正常逻辑
                let selectdata = ytProps.transferTable.getTransferTableSelectedValue()
                if (selectdata && selectdata.head && selectdata.head.length > 0) {
                    return;
                }
                window.pageFyytClick(null);
            })
        }
    }
    // 关联发票关闭
    closeInvoiceRelate = () => {
        this.setState({showInvoiceRelate: false})
    }
    // 票夹关闭
    closeWallet = () => {
        this.setState({showInvoiceWallet: false})
    }

    // 本地上传关闭
    closeUploadInvoice = () => {
        this.setState({showUploadInvoice: false})
    }

	// 快速分摊关闭
    closeQuickShare = () => {
        this.setState({showQuickShare: false})
    }

    getHeadValueByKey = (key) => {
        return this.props.form.getFormItemsValue('head', key)
    }

    getCardData = () => {
        let rowDataList = []
        let bodyarr = [];
        let hideTable = this.state.hideTables;

        let bodys = Object.values(window.presetVar.body);
        bodys.forEach((one) => {
            if (hideTable.indexOf(one) < 0) {
                bodyarr[bodyarr.length] = one;
            }
        })
        bodyarr.forEach(bodyCode => {
            let list = this.props.cardTable.getAllRows(bodyCode)
            list = list.filter(e => e.status != '3')  // deleted : '3'
            rowDataList = [...rowDataList, ...list]
        })
        return rowDataList;
    }

    hideTableUploader = () => {
        this.setState({...this.state, showTableUploader: false})
    }

    beforeDeleteAttachment = async (item) => {
        function getResult() {
            return new Promise((resolve, rej) => {
                requestApi.canDelete({
                    data: {attchment: item},
                    success: (data) => {
                        if(data.data.checkResult === 'true'){
                            resolve(true)
                        } else {
                            toast({content: data.data.checkResultMsg, color: 'danger'})
                            resolve(false)
                        }
                    }
                })
            })
        }
        const ret = await getResult()
        return ret;
    }

    renderErrorCenterState () {
        const { props } = this
        const status = props.form.getFormItemsValue('head', 'saga_status')
        if (!status || status.value !== '1') return null;

        this.props.button.toggleErrorStatus('head',{
            isError: true
        })

        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: 'head',
            billtype: status.value,
            billpkname: 'pk_jkbx',
            dataSource: 'erm.expenseaccount.expenseaccount.card'
        }
        return props.socket.connectMesg(param)
    }

	getQuickShareParams() {
        const paramdata = {}
        let billdata = this.props.createHeadAfterEventData('20110ETEA_2641_IWEB', "head", window.presetVar.lsBodys);
        const pk_org = this.props.form.getFormItemsValue('head', 'pk_org')
        paramdata.pk_org = pk_org
        billdata.card.head.userjson = JSON.stringify(paramdata);
        return {billdata: billdata.card, pk_org }
    }

    getQuickShareAmount() {
        let vat_amount = this.props.form.getFormItemsValue('head', 'vat_amount')
        if(this.currentModuleId === 'er_cshare_detail') {
            const index_obj =  this.props.cardTable.getClickRowIndex('er_cshare_detail')
            if(index_obj && index_obj.record && index_obj.record.status != '3' && rowExists(this.props, 'er_cshare_detail', index_obj.record.rowid)) {
                vat_amount = index_obj.record.values.assume_amount
            }
        }
        return vat_amount
    }

    onQuickShareClick(rulePk) {
        // 选择快速分摊规则,开始快速分摊
        if(rulePk) {
            const paramdata = {
                "value":'',
                "tableid":'headform',
                "field":'',
                "uistate": window.presetVar.pagestatus,
                "tradetype": window.presetVar.tradetype,
                "oldvalue":'',
                "pagecode": window.presetVar.pagecode,
                "appcode": window.presetVar.appcode
            }
            //是否选择继续分摊
            if(this.currentModuleId === 'er_cshare_detail') {
                const index_obj =  this.props.cardTable.getClickRowIndex('er_cshare_detail')
                if(index_obj && index_obj.record && index_obj.record.status != '3' && rowExists(this.props, 'er_cshare_detail', index_obj.record.rowid)) {
                    paramdata.changeRowId = index_obj.record.rowid
                    paramdata.tableid = 'er_cshare_detail'
                }
            }
            let billdata = this.props.createHeadAfterEventData('20110ETEA_2641_IWEB', "head", window.presetVar.lsBodys);
            // billdata.card.bodys.er_cshare_detail.rows =  window.ecshare_rule_data.rows
             
            const pk_org = this.props.form.getFormItemsValue('head', 'pk_org')
            paramdata.pk_org = pk_org.value
            paramdata.shareRulePk = rulePk
            billdata.card.head.userjson = JSON.stringify(paramdata);
            billdata.templetid = this.props.meta.getMeta().pageid;
            requestApi.quickShare({data: billdata.card, success:(response) => {
                //分摊成功后勾选分摊、设置费用承担单位不可编辑、分摊明细页签可见
                const isShare = this.props.form.getFormItemsValue('head', 'iscostshare').value;
                if(!isShare) {
                    this.props.form.setFormItemsValue('head', { iscostshare: { value: true } });
                    this.props.form.setFormItemsDisabled('head', { fydwbm_v: true });
                    let hideTables = this.state.hideTables
                    let index = hideTables.findIndex(item=>item==='er_cshare_detail')
                    if(index>-1){
                        hideTables.splice(index,1)
                        this.setState({ hideTables:hideTables });
                    }
                }
                setImportConfig(this);//设置导入按钮
                Object.values(presetVar.body).forEach((body) => {
                    if (response.data.bodys[body]) {
                        if(body === 'er_cshare_detail') {
                            this.props.cardTable.setTableData(body, response.data.bodys[body]);
                        } else {
                            this.props.cardTable.updateTableData(body, response.data.bodys[body]);
                        }
                    }
                });
            }})
        }
    }
    toggleAuditSideBar(fromBtn) {
        //判断是否是提交 按钮或者保存提交按钮
        fromBtn = fromBtn||window.presetVar.fromBtn


        let param = {};
        param.pk_group = this.getFormHeadValueByKey('pk_group'); // "集团pk"
        param.billtypecode = this.getFormHeadValueByKey('pk_billtype'); // "单据类型code"
        param.tradetypecode = this.getFormHeadValueByKey('djlxbm')?this.getFormHeadValueByKey('djlxbm'):this.getFormHeadValueByKey('pk_billtype'); // " 交易类型code"
        param.billid = this.getFormHeadValueByKey('pk_jkbx'); // "单据主键pk"
        param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        param.iscreate = "Y"   // 注意应该是制单首次保存传Y,浏览态去掉这个参数！！！是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入 做初始化 智能审批
        param.isEdit = true;

        // param.pk_group = "0001A510000000000NKA"; // "集团pk"
        // param.billtypecode = "267X"; // "单据类型code"
        // param.tradetypecode = "267X"; // " 交易类型code"
        // param.billid = "1001A510000000003V27"; // "单据主键pk"
        // param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        // param.iscreate =  "Y"  // 是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入
        // param.isEdit = true; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        console.log('param111111111111111111111',param,this.props.getUrlParam("isfromczh"),this.props.getUrlParam("status"),this.props.getUrlParam("scene"))
        if(!param.billid){
            return
        }
        const isfromczh = this.props.getUrlParam("isfromczh")
        //展示后的回调
        this.auditSidebar.showSidebar(param,null,()=>{
            // this.auditSidebar.refreshSidebar()
            setTimeout(()=>{
                const auditSidebarObj = this.auditSidebar.getSidebarStatistical()
                console.log('1111111',auditSidebarObj)
                const {pointTree} = auditSidebarObj
                if(!pointTree.length){
                    this.setState({
                        showAuditSidebar:false
                    })
                    window.presetVar.auditCanSave = 0
                    return
                }
                this.setState({
                    showAuditSidebar:true
                })

                for(let i=0;i<pointTree.length;i++){
                    const leaf = pointTree[i]
                    if(leaf.children&&leaf.children.length){
                        if(leaf.children.some(item=>item.ispass==='N')){
                            window.presetVar.auditCanSave = 3 //目前需求只要有不通过的就提示风险
                            //1 严格控制 2风险提示
                            // if(leaf.children.some(item=>item.values.controltype=='1')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 1
                            //     break
                            // }else if(leaf.children.some(item=>item.values.controltype=='2')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 2
                            //     break
                            // }
                        }else{
                            window.presetVar.auditCanSave = 0
                        }
                    }
                }

                //展示风险弹窗
                if((fromBtn==='saveSubmit'||isfromczh)&&this.props.getUrlParam("status")==='browse'&&window.presetVar.auditCanSave>0){
                    let multiLang = this.props.MutiInit.getIntl(2011);
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: multiLang && multiLang.get('201102BCLF-0016'),
                        content: multiLang && multiLang.get('201102BCLF-0062'),
                        cancelBtnName:'收回',
                        beSureBtnClick: ()=>{
                            window.presetVar.auditCanSave = 0

                        },
                        cancelBtnClick: () => {
                            pageButtonClick.call(this)[pageButton.billRecall]();

                        }
                    })
                }
            })

        })

    }
    getFormHeadValueByKey(key) { // 根据 form 获取 head 中的值
        return this.props.form.getFormItemsValue("head", key).value || '';
    }


    //弹出隐藏层
    closeInvoiceWalletModal(params) {
        this.setState({showInvoiceWallet: false}) ;
    }

    //关联申请单的回调
    confirmRelate(){

        this.setState({showApplicationFormModal:false})
    }


    render() {
        let { target,djzt,showAuditSidebar } = this.state;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let btnModalConfig = {
            [pageButton.pageDel]: {
                // "2011-0004": "删除"
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005'),
            },
            [pageButton.billInvalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010'),
                beSureBtnClick: this.billInvalid.bind(this)
            }
        }
        //单据分享的内容-begin
        let content = (
            <div style={{ height: '130px', width: '237px' }}>
                {/*"201102BCLF-0005": "分享给",*/}
                <p style={{ color: '#111', height: '50px' }}>{multiLang && multiLang.get('201102BCLF-0005')}</p>
                <AllUserGridRef
                    value={this.state.allUserGridRefValue}
                    onChange={(data) => {
                        this.setState({
                            allUserGridRefValue: data
                        });
                    }}
                    queryCondition={() => {
                        return { 'enablestate': 2 }
                    }}
                    isMultiSelectedEnabled={true}
                />
                <div style={{ height: '90px', marginBottom: '78px', marginTop: '30px' }}>

                    <NCButton
                        style={{ float: 'right', marginBottom: '20px' }}
                        colors="info"
                        onClick={
                            () => {
                                this.setState({
                                    showBillShare: false,
                                    allUserGridRefValue: {}
                                })
                            }
                        }
                        // "2011-0002": "取消",
                        size="sm">
                        {multiLang && multiLang.get('2011-0002')}
                    </NCButton>
                    <NCButton
                        style={{ float: 'right' }}
                        colors="primary"
                        onClick={
                            () => {
                                //分享逻辑
                                if (this.state == null || this.state.allUserGridRefValue == null || this.state.allUserGridRefValue == undefined)
                                    return;
                                let bodys = Object.values(window.presetVar.body);
                                let bodyarr = [];
                                let hideTable = this.state.hideTables;
                                bodys.forEach((one) => {
                                    if (hideTable.indexOf(one) < 0) {
                                        bodyarr[bodyarr.length] = one;
                                    }
                                })
                                let showData = this.props.createExtCardData(this.props.meta.getMeta().code, "head", bodyarr);
                                let paramdata = {};
                                let paramurl = getRequest1(parent.window.location.hash);
                                let billid = this.props.getUrlParam("id") || this.props.getUrlParam("billid");
                                paramdata.pagecode = paramurl.p;
                                paramdata.appcode = paramurl.c;
                                paramdata.billid = billid;
                                paramdata.tradetype = window.presetVar.tradetype;
                                let receiveruser = "";
                                if (this.state.allUserGridRefValue != null && this.state.allUserGridRefValue.length > 0) {
                                    for (let m = 0; m < this.state.allUserGridRefValue.length; m++)
                                        receiveruser += this.state.allUserGridRefValue[m].refpk + ","
                                }
                                paramdata.receiveruser = receiveruser;
                                showData.head.userjson = JSON.stringify(paramdata);
                                requestApi.billShare({
                                    data: showData,
                                    success: (data) => {
                                        this.setState({
                                            showBillShare: false
                                        })
                                        this.state.allUserGridRefValue = null;
                                        toast({ content: multiLang && multiLang.get("201102BCLF-0043"), color: 'success' });
                                    }
                                });
                                return;
                            }
                        }
                        // "201102BCLF-0006": "分享",
                        size="sm">
                        {multiLang && multiLang.get('201102BCLF-0006')}
                    </NCButton>
                </div>
            </div>
        )

        let status = this.props.getUrlParam("status");
        let scene = this.props.getUrlParam("scene");

        if(status==='browse') {
            this.currentModuleId = null;
        }

        //侧拉抽屉
        let {DragWidthCom } = this.props

        console.log('copyFromBillId====',this.props.getUrlParam('copyFromBillId'))
        //单据分享的内容-end
        return (
            <div className='billWrapper'>
                {this.renderErrorCenterState()}

                <DragWidthCom
                    leftDom={
                        <BillStyle
                            {...this.props}
                        >
                            <BillHead title={this.state.transtype_name}
                                tipShow={this.state.isShowover}
                                refreshButtonEvent={refreshButtonClick.bind(this)}
                            >

                                <ButtonGroup
                                    areaId="head"
                                    buttonEvent={pageButtonClick.bind(this)}
                                    modalConfig={btnModalConfig}
                                    sagasButtonVisible={this.props.getUrlParam('copyFromBillId')?false:true}
                                />
                                <Form
                                    areaId="head"
                                    onAfterEvent={afterEvent.bind(this)} />
                            </BillHead>

                            <BillBody>

                                <NCPopover
                                    rootClose={false}
                                    placement="leftTop"
                                    content={content}
                                    show={this.state.showBillShare}
                                    id="billshare"
                                >
                                    <div
                                        colors="primary"
                                        id="billshareDiv"
                                        className={(status == 'browse' && scene != 'notice') == true ? "billshare-icon-show" : "billshare-icon-hide"}
                                        onClick={
                                            () => {
                                                this.setState({
                                                    showBillShare: true
                                                })
                                            }
                                        }
                                    >
                                        {/*<div  style={{ fontSize: '17px',color: '#a91a1a' }}> {multiLang && multiLang.get('201102BCLF-0007')}*/}
                                        <i className='iconfont icon-fenxiang share' ></i>
                                        {/*</div>*/}
                                    </div>
                                </NCPopover>


                                <CardTableGroup
                                    excludeTableAreaId={null}
                                    totalItemCode="vat_amount"
                                    totalItemCodeByAreas={ //
                                        {
                                            'accrued_verify': 'verify_amount',
                                            'er_bxcontrast': 'cjkybje',
                                            'er_cshare_detail': 'assume_amount',
                                            'invoice_Detail': 'jshj'
                                        }
                                    }
                                    modelAddRow = {(scope, moduleId, index, record) => {
                                        setDefautValueAfterBodyAdd.call(this, this.props, moduleId, index)
                                    }}
                                    modelSave={pageButtonClick.call(this)['pageSave']}
                                    //侧拉删除事件,2012版本接口变化,通过回调事件自行调用
                                    modelDelRowBefore={(scope, moduleId, index, record) => {
                                        if ((record.status == 1 || record.status == 0) && record.values.pk_mtapp_detail && record.values.pk_mtapp_detail.value) {
                                            toast({ content: '由申请生成的报销明细不允许删除,请知悉!', color: 'danger' })
                                            return false
                                        }
                                        this.props.cardTable.delRowsByIndex(moduleId, index)
                                    }}
                                    onBeforeEvent={beforeEvent.bind(this)}
                                    onAfterEvent={afterEvent.bind(this)}
                                    invisibleTables={this.state.hideTables}
                                    onBatchChange={onBatchChange.bind(this)}
                                    onRowClick={(props, moduleId) => { this.currentModuleId = moduleId }}//记录在点击快速分摊时最后是不是选中的分摊明细，实现可以点击其它页签取消选择的效果
                                >
                                    <MultiButtonGroup buttonEvent={tableButtonClick(window._tableButtonsClick).bind(this)} />
                                </CardTableGroup>

                                {
                                    this.state.showUploader && < NCUploader
                                        disableButton={this.state.uploaderBtnDisable}
                                        billId={this.props.getUrlParam('id') || this.props.getUrlParam("billid") ? this.props.getUrlParam('id') || this.props.getUrlParam("billid") : this.state.billId}
                                        customize={{ 'pk_billtypecode': this.props.getUrlParam('tradetype'), "djdl": "bx" }}
                                        beforeDelete={this.beforeDeleteAttachment.bind(this)}
                                        target={target}
                                        onHide={this.onHideUploader.bind(this)}
                                        customInterface={
                                            {
                                                queryLeftTree: "/nccloud/erm/pub/ErmAttachmentTreeNodeQueryAction.do",
                                                queryAttachments: "/nccloud/erm/pub/ErmAttachmentQueryAction.do"
                                            }
                                        }
                                        placement={'bottom'} 
                                        formatGroupMoveList = { (groupList) => {
                                            return groupList.filter( (item, index) => (item.disableButton && !item.disableButton.includes("fs_group_edit") || item.disableButton === undefined));
                                        }}
                                        />
                                }

                                {/* 表体关联的发票查看 */}
                                {
                                    this.state.showTableUploader && < NCUploader
                                        isApprove={true}
                                        billId={this.props.getUrlParam('id') || this.props.getUrlParam("billid") ? this.props.getUrlParam('id') || this.props.getUrlParam("billid") : this.state.billId}
                                        target={target}
                                        onHide={this.hideTableUploader.bind(this)}
                                        customInterface={
                                            {
                                                queryLeftTree: "",//"/nccloud/erm/pub/ErmAttachmentTreeNodeQueryAction.do",
                                                queryAttachments: "/nccloud/erm/erminvoice/ErmInvoiceSingleLinkQueryAction.do"
                                            }
                                        }
                                        customize={this.state.reqTableAttachParam}
                                        disableButton={true}
                                        placement={'bottom'} />
                                }


                                <div>
                                    <ApproveDetail
                                        show={this.state.ShowApproveDetail}
                                        close={this.closeApprove}
                                        billtype={this.state.billtype}
                                        billid={this.state.billId}
                                    />
                                </div>
                            </BillBody>

                        </BillStyle>
                    }
                    rightDom={
                        this.auditSidebar.createComponent()
                    }
                    aside="right"
                    defLeftWid={showAuditSidebar && djzt !== '0' && status === 'browse' && (scene !== 'sscermlink' && scene !== "linksce" && scene !== "lc" && scene !== "approve" && scene !== "approvesce" && scene !== 'zycl')
                        ? "20%" : '0%'}
                >
                </DragWidthCom>
                {this.state.showApplicationFormModal ? <ExpenseaccountForPull
                    close={() => this.setState({ showApplicationFormModal: false })}
                    showApplicationFormModal={this.state.showApplicationFormModal}
                    pageCode={window.presetVar.pagecode}
                    appcode={window.presetVar.appcode}
                    hideTables={this.state.hideTables}
                    parentbodys={window.presetVar.body}
                    confirmHide={(hideTables)=>{
                        this.setState({hideTables})
                    }}
                    // pageId = {window.presetVar.pageId}
                    parentProps={this.props}
                    confirmRelate={this.confirmRelate.bind(this)}
                /> : null}
                <NCModal size="xlg" show={
                    this.state.showCJKModal
                }
                    onHide={
                        this.closecjk
                    }

                >
                    <NCModal.Header closeButton="true">
                        {/*"201102BCLF-0002": "冲借款",*/}
                        <NCModal.Title >{multiLang && multiLang.get('201102BCLF-0002')}</NCModal.Title>
                    </NCModal.Header>

                    <NCModal.Body>
                        <Cjk setDefaultSelectedJk={this.setDefaultSelectedJk} showCJKModal={this.state.showCJKModal} />
                    </NCModal.Body>
                </NCModal>

                <NCModal size="xlg"
                    show={
                        this.state.showFyytModal
                    }
                    onHide={
                        this.closefyyt
                    }

                >
                    <NCModal.Header closeButton="true">
                        {/*"201102BCLF-0003": "核销预提"*/}
                        <NCModal.Title >{multiLang && multiLang.get('201102BCLF-0003')}</NCModal.Title>
                    </NCModal.Header>

                    <NCModal.Body >
                        <Fyyt showFyytModal={this.state.showFyytModal} setDefaultSelectedYt={this.setDefaultSelectedYt} />
                        {/* <div className="area-content" >
            <iframe src={window.location.protocol+"//"+window.location.host+"/nccloud/resources/erm/expenseaccount/expenseaccount4Fyyt/card/index.html#status=add&tradetype="+window.presetVar.tradetype}
        width="100%" className="cjkmodel"></iframe>
            </div> */}
                        <div>

                        </div>
                    </NCModal.Body>
                </NCModal>

                {/* 联查费用申请单 */}
                <LinkQueryFysqModel
                    show={this.state.showLinkQueryFysqModel}
                    linkData={this.state.linkData}
                    close={() => this.setState({showLinkQueryFysqModel: false})}
                    tradetype={window.presetVar.tradetype}
                    openBillId={this.state.billId}
                    {...this.props} />

                {/* 联查费用预提单 */}
                <LinkQueryFyytModel
                    show={this.state.showLinkQueryFyytModel}
                    linkData={this.state.linkData}
                    close={() => this.setState({ showLinkQueryFyytModel: false })}
                    tradetype={window.presetVar.tradetype}
                    openBillId={this.state.billId}
                    {...this.props} />

                {/* 联查借款单 */}
                <LinkQueryJkbxModel
                    show={this.state.showLinkQueryJkbxModel}
                    linkData={this.state.linkData}
                    close={() => this.setState({ showLinkQueryJkbxModel: false })}
                    tradetype={window.presetVar.tradetype}
                    openBillId={this.state.billId}
                    {...this.props} />
                <div>
                    <Inspection
                        show={this.state.showLinkBudget}
                        sourceData={this.state.sourceData}
                        cancel={this.cancel.bind(this)}
                        affirm={this.affirm.bind(this)}
                    />
                </div>
                <div>
                    {/*"201102FYYT-0003": "指派",*/}
                    {this.state.compositedisplay ? <ApprovalTrans
                        title={multiLang && multiLang.get('201102FYYT-0003')}
                        data={this.state.compositedata}
                        display={this.state.compositedisplay}
                        getResult={this.getAssginUser.bind(this)}
                        cancel={this.turnOff.bind(this)}
                    /> : ""}

                </div>
                {/* 关联发票 */}
                <NCModal size="xlg" show={ this.state.showInvoiceRelate }
                    onHide={ this.closeInvoiceRelate }
                >
                    <NCModal.Header closeButton="true">
                        <NCModal.Title >{multiLang && multiLang.get('201103INUP-0041')}</NCModal.Title>
                    </NCModal.Header>

                    <NCModal.Body>
                        <InvoiceWallet
                            showInvoiceWalletModal={this.state.showInvoiceRelate}
                            getTradeType={this.getHeadValueByKey}
                            getCardData={this.getCardData}
                            // 是否是点击票夹按钮  true 是； false 否
                            iswallet = {false}
                            // 确定按钮回调函数
                            associatedApplication = {(params) => {
                                // 勾选的列表pk
                                let { checkArr } = params;
                                relateVoiceEvent.call(this,this.props,this.state.currentRowInvoiceRelate,false,checkArr)

                            }}
                            showDiv = {this.showDiv}
                        />
                    </NCModal.Body>
                </NCModal>

                {/* 票夹 */}
                <NCModal size="xlg" show={ this.state.showInvoiceWallet }
                    onHide={ this.closeWallet }
                >
                    <NCModal.Header closeButton="true">
                        <NCModal.Title >{multiLang && multiLang.get('201103INUP-0006')}</NCModal.Title>
                    </NCModal.Header>

                    <NCModal.Body>
                        <InvoiceWallet
                            showInvoiceWalletModal={this.state.showInvoiceWallet}
                            getTradeType={this.getHeadValueByKey}
                            getCardData={this.getCardData}
                            // 是否是点击票夹按钮  true 是； false 否
                            iswallet = {true}
                            // 确定按钮回调函数
                            associatedApplication = {(params) => {
                                // 勾选的列表pk
                                let { checkArr } = params;
                            }}
                            closeInvoiceWalletModal = {this.closeInvoiceWalletModal}
                            multiLangJson={this.multiLangJson || {}}
                        />
                    </NCModal.Body>
                </NCModal>

                {/* 发票上传 */}
                <NCModal size="xlg" show={ this.state.showUploadInvoice } keyboard={false}
                         onHide={ this.closeUploadInvoice }
                >
                    <NCModal.Header closeButton="true">
                        <NCModal.Title >{multiLang && multiLang.get('201103INUP-0007')}</NCModal.Title>
                    </NCModal.Header>

                    <NCModal.Body>
                        <UploadInvoice hideTables={this.state.hideTables}
                            confirmHide={(hideTables) => {
                                this.setState({ hideTables })
                            }} hide={this.closeUploadInvoice.bind(this)} parentProps={this.props} multiLang={this.multiLangJson || {}} />
                    </NCModal.Body>
                </NCModal>

                {/* 查看借款情况 */}
                {
                    this.state.showLoanDetailModel ?
                    <NCModal
                        size="xlg"
                        show = { this.state.showLoanDetailModel }
                        onHide = { () => this.setState({showLoanDetailModel: false})}
                    >
                        <NCModal.Header closeButton="true">
                                {/*"201107TZD-0002": "借款情况",*/}
                                <NCModal.Title >{multiLang && multiLang.get('201107TZD-0002')}</NCModal.Title>
                        </NCModal.Header>
                        <NCModal.Body>
                                <LoanDetail  showLoanDetailModel={this.state.showLoanDetailModel}  />
                        </NCModal.Body>
                    </NCModal>
                    : null
                }

				{/* 快速分摊 */}
                <QuickShare size="lg" show={ this.state.showQuickShare } title={ multiLang && multiLang.get('201103INUP-0014') }
                    onHide={ this.closeQuickShare.bind(this) }
                    getQuickShareParams={this.getQuickShareParams.bind(this)}
                    getQuickShareAmount={this.getQuickShareAmount.bind(this)}
                    onQuickShareClick={this.onQuickShareClick.bind(this)}
                    parentProps={this.props}
                />
                <NCLoading
                    fullScreen
                    showBackDrop={true}
                    show={this.state.isShowLoading}
                />
            </div>
        )
    }
}

jkbxBillCard = createPage({
    mutiLangCode: '2011',
    billinfo: {
        billtype: 'extcard',
        pagecode: "201102BCLF_C",
        headcode: "head",
        bodycode: ["arap_bxbusitem","other","zsitem","bzitem","er_cshare_detail","er_bxcontrast","accrued_verify"]
    },
    orderOfHotKey: ["arap_bxbusitem", "other", "zsitem", "bzitem"]
})(jkbxBillCard);

export default jkbxBillCard;
